<template>
  <div class="card-container">
    <div class="search-bar">
      <el-input  placeholder="请输入搜索内容" v-model="searchForm.content"></el-input>
      <el-button type="primary" icon="el-icon-search" @click="handleSearchPosts" plain>搜索</el-button>
      <el-button type="success" icon="el-icon-refresh-left" @click="resetSearch" plain>重置</el-button>
    </div>
  <el-card v-for="(post, index) in posts" :key="index">
    <div class="forum-post" >
      <div class="user-info">
        <img :src="post.icon" alt="User Avatar" class="avatar">
        <div class="user-details">
          <span class="nickname">{{ post.realname }}</span>
          <span class="post-time">{{ post.datetime|formatter }}</span>
        </div>
      </div>

      <div class="post-content">
        <div v-if="!postExpanded[index]" v-html="post.content.slice(0, 700) + '...'"></div>
        <div v-else v-html="post.content"></div>
        <el-button v-if="post.content.length > 700" type="text" @click="toggleExpand(index)" class="expand-button">
          {{ postExpanded[index] ? '收起' : '展开' }}
        </el-button>
      </div>

      <div class="reply-section">
        <el-button type="text" @click="toggleReply(index)" class="expand-button">评论</el-button>
        <div v-if="replyVisible[index]" >
          <el-input
              type="textarea"
              placeholder="请输入评论内容"
              v-model="replyForm[post.id]"
              class="reply-box"
          ></el-input>
          <el-button type="primary" @click="submitComment(post.id, index)" plain>评论</el-button>
          <div v-for="(comment, commentIndex) in comments[post.id]" :key="commentIndex" class="comment-item">
            <img :src="comment.icon" alt="User Avatar" class="avatar">
            <div class="user-details">
              <span class="nickname">{{ comment.realname }}</span>
              <span class="post-time">{{ comment.commenttime | formatter }}</span>
            </div>
            <div class="comment-content">
              {{ comment.readercomment }}
            </div>
          </div>
          <div>
            <el-pagination
                @size-change="commentSizeChange"
                @current-change="commentCurrentChange"
                :current-page="commentPageData.currentPage"
                :page-sizes="[10, 15, 20, 25]"
                :page-size=commentPageData.pageSize
                layout="total, sizes, prev, pager, next, jumper"
                :total="commentPageData.total">
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
  </el-card>
    <div>
      <el-pagination
          @size-change="sizeChange"
          @current-change="currentChange"
          :current-page="pageData.currentPage"
          :page-sizes="[10, 15, 20, 25]"
          :page-size=pageData.pageSize
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageData.total">
      </el-pagination>
    </div>
    <div class="post-button">
      <el-button type="info" @click="dialogVisible = true" style="font-size: 40px;" icon="el-icon-edit-outline" plain circle  class="custom-size"></el-button>
    </div>

    <el-dialog
        title="发布贴子"
        :visible.sync="dialogVisible"
        width="70%"
        :before-close="handleClose">

      <div style="border: 1px solid #ccc;">
        <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editor"
            :defaultConfig="toolbarConfig"
            :mode="mode"
        />
        <Editor
            style="height: 395px; overflow-y: hidden;"
            v-model="postsForm.content"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="onCreated"
        />
      </div>

      <span slot="footer" class="dialog-footer">
    <el-button @click="cancelDialog">取 消</el-button>
    <el-button type="primary" @click="submitForm" plain>确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import axios from "axios";
export default {
  name: "Forum",
  components: { Editor, Toolbar },
  data() {
    return {
      postsForm:{
        readerid:'',
        content:'',
        datetime:''
      },
      dialogVisible: false,
      searchForm:{
        content:''
      },
      commentPageData:{
        currentPage:1,
        pageSize:10,
        total:0
      },
      pageData:{
        currentPage:1,
        pageSize:10,
        total:0
      },
      editor: null,
      toolbarConfig: {},
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF:{
          uploadImage:{
            server: 'http://localhost:8888/notice/upload',
            fieldName: 'file',
            // 单个文件的最大体积限制，默认为 2M
            maxFileSize: 5 * 1024 * 1024, // 1M

            // 最多可上传几个文件，默认为 100
            maxNumberOfFiles: 10,

            // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
            allowedFileTypes: ['image/*'],
            headers:{
              Authorization:localStorage.getItem('token')
            },
            // 单个文件上传成功之后
            // onSuccess(file: File, res: any) {  // TS 语法
            onSuccess(file, res) {          // JS 语法
              console.log(`${file.name} 上传成功`, res)
            },
            // 单个文件上传失败
            // onFailed(file: File, res: any) {   // TS 语法
            onFailed(file, res) {           // JS 语法
              console.log(`${file.name} 上传失败`, res)
            },
            // 上传错误，或者触发 timeout 超时
            // onError(file: File, err: any, res: any) {  // TS 语法
            onError(file, err, res) {               // JS 语法
              console.log(`${file.name} 上传出错`, err, res)
            },
            // 自定义插入图片
            // customInsert(res: any, insertFn: InsertFnType) {  // TS 语法
            customInsert(res, insertFn) {                  // JS 语法
              // res 即服务端的返回结果
              console.log(res.data)
              // 从 res 中找到 url alt href ，然后插入图片
              insertFn(res.data, "", "")
            }
          },
          uploadVideo:{
            server: 'http://localhost:8888/notice/upload',
            fieldName: 'file',
            // 单个文件的最大体积限制，默认为 2M
            maxFileSize: 200 * 1024 * 1024, // 5M

            // 最多可上传几个文件，默认为 100
            maxNumberOfFiles: 10,

            // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
            allowedFileTypes: ['video/*'],
            headers:{
              Authorization:localStorage.getItem('token')
            },
            // 单个文件上传成功之后
            // onSuccess(file: File, res: any) {  // TS 语法
            onSuccess(file, res) {          // JS 语法
              console.log(`${file.name} 上传成功`, res)
            },
            // 单个文件上传失败
            // onFailed(file: File, res: any) {   // TS 语法
            onFailed(file, res) {           // JS 语法
              console.log(`${file.name} 上传失败`, res)
            },
            // 上传错误，或者触发 timeout 超时
            // onError(file: File, err: any, res: any) {  // TS 语法
            onError(file, err, res) {               // JS 语法
              console.log(`${file.name} 上传出错`, err, res)
            },
            // 自定义插入图片
            // customInsert(res: any, insertFn: InsertFnType) {  // TS 语法
            customInsert(res, insertFn) {                  // JS 语法
              // res 即服务端的返回结果
              console.log(res.data)
              // 从 res 中找到 url alt href ，然后插入图片
              insertFn(res.data, "")
            }
          }
        }
      },
      mode: 'default',
      posts: [],
      postExpanded: {},
      replyVisible: {},
      replyForm: {},
      comments: {}
    };
  },
  created() {
    this.getPosts()
    this.getCustomReaderComment()
  },
  methods: {
    async submitComment(postId, index) {
      const commentContent = this.replyForm[postId];
      if (!commentContent) {
        this.$message.warning('请输入评论内容');
        return;
      }

      try {
        const params = {
          postsid: postId,
          readercomment: commentContent,
          readerid:sessionStorage.getItem('id'),
          commenttime:this.getCurrentDate()
        };
        await this.$axios.post('readerComment/addReaderComment', params);
        this.$message.success('评论成功');

        // 清空评论框
        this.replyForm[postId] = '';
        this.$set(this.comments, postId, []);
        // 刷新评论列表
        await this.getCustomReaderComment();
      } catch (error) {
        this.$message.error('评论失败，请重试');
      }
    },
    async getCustomReaderComment() {
      const params = { ...this.commentPageData, postsid: this.id };
      const { data: res } = await this.$axios.get("readerComment/getCustomReaderComment", { params });
      this.commentPageData.total = res.data.total;
      this.comments = {};
      // 将评论数据按照 postsid 存储到 comments 对象中
      res.data.records.forEach(comment => {
        if (!this.comments[comment.postsid]) {
          this.$set(this.comments, comment.postsid, []);
        }
        this.comments[comment.postsid].push({
          icon: comment.icon,
          realname: comment.realname,
          commenttime: comment.commenttime,
          readercomment: comment.readercomment,
        });
      });
    },
    async getPosts() {
      const params = {...this.pageData, ...this.searchForm};
      const { data: res } = await this.$axios.get("posts/getCustomPosts", { params });
      this.tableData = res.data.records;
      this.pageData.total = res.data.total;
      this.posts = res.data.records.map(record => ({
        icon: record.icon,
        realname: record.realname,
        datetime: record.datetime,
        content: record.content,
        id: record.id,
      })).sort((a, b) => new Date(b.datetime) - new Date(a.datetime));
      this.posts.forEach((_, index) => {
        this.$set(this.postExpanded, index, false);
      });
    },
    submitForm() {
      this.postsForm.datetime = this.getCurrentDate()
      this.postsForm.readerid = sessionStorage.getItem('id')
      axios.post('posts/addPosts',this.postsForm).then(res=>{
        if (res.data.success) {
          this.$message.success('发布成功')
          this.dialogVisible = false;
          this.getPosts()
          this.postsForm = {content: ''}
        } else {
          this.$message.error('发布失败')
        }
      })
    },
    cancelDialog() {
      this.dialogVisible = false;
      this.postsForm = {content: ''}
    },
    handleSearchPosts() {
      this.pageData.currentPage = 1
      this.getPosts()
    },
    resetSearch() {
      this.searchForm.content = ''
      this.pageData.currentPage = 1;
      this.getPosts()
    },
    currentChange(val){
      this.pageData.currentPage=val
      this.getPosts()
    },
    sizeChange(val){
      this.pageData.pageSize=val
      this.getPosts()
    },
    commentCurrentChange(val){
      this.commentPageData.currentPage=val
      this.getCustomReaderComment()
    },
    commentSizeChange(val){
      this.commentPageData.pageSize=val
      this.getCustomReaderComment()
    },
    getCurrentDate() {
      const now = new Date();
      return now.toISOString();
    },
    toggleExpand(index) {
      this.$set(this.postExpanded, index, !this.postExpanded[index]);
    },
    toggleReply(index) {
      this.$set(this.replyVisible, index, !this.replyVisible[index]);
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            this.postsForm = {
              content: '',
            }
            done();
          })
          .catch(_ => {});
    },
    onCreated(editor) {
      this.editor = Object.seal(editor)
    },
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  filters:{
    formatter(date){
      return new Date(date).toLocaleDateString(
          'zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
          }
      )
    }
  }
}
</script>

<style scoped>
.custom-size {
  width: 80px; /* 根据需要调整宽度 */
  height: 80px; /* 根据需要调整高度 */
  padding: 0; /* 移除默认的内边距 */
}
.post-button {
  position: fixed;
  bottom: 310px;
  right: 100px;
  z-index: 1000;
}
.card-container {
  display: flex;
  justify-content: center;
  width: 100%;
  flex-wrap: wrap;
}
.forum-post {
  display: flex;
  flex-direction: column;
}
.el-card {
  width: 70%;
  margin: 5px 0;
}
.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.search-bar {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  margin-right: 320px;
}
.el-input {
  width: 300px;
  margin-right: 10px;
}
.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.user-details {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.nickname {
  font-weight: bold;
  margin-right: 10px;
}

.post-time {
  color: #999;
  font-size: 12px;
}

.post-content {
  display: flex;
  flex-direction: column;
  line-height: 1.6;
  margin-left: 50px;
  position: relative;
}
.expand-button {
  display: inline-block;
  margin-left: auto;
  vertical-align: top;
}
.reply-section {
  display: flex;
  flex-direction: column;
  line-height: 1.6;
  margin-left: 50px;
  position: relative;
}
.reply-section .el-button {
  margin-top: 10px;
}
.reply-box {
  margin-top: 10px;
  display: flex;
  width: 90%;
}
.comment-item {
  display: flex;
  flex-direction: column;
  margin-top: 10px;
}

.comment-content {
  margin-left: 50px;
  line-height: 1.6;
}
.el-pagination{
  margin-top: 10px;
}
</style>